package main

import (
	"fmt"
	"regexp"
	"strconv"
)

var chineseToArabic = map[string]int{
	"零": 0, "一": 1, "二": 2, "三": 3, "四": 4,
	"五": 5, "六": 6, "七": 7, "八": 8, "九": 9,
}

var unitMap = map[string]int{
	"":  1, // 默认单位
	"十": 10,
	"百": 100,
	"千": 1000,
	"万": 10000,
	"亿": 100000000,
}

func convertChineseNumber(text string) (int, error) {
	re := regexp.MustCompile(`(\d+|[一二三四五六七八九])([十百千万亿]?)`)
	matches := re.FindAllStringSubmatch(text, -1)
	result := 0
	currentValue := 0
	lastUnitValue := 1

	for _, match := range matches {
		var number int
		if arabic, err := strconv.Atoi(match[1]); err == nil {
			number = arabic
		} else if num, ok := chineseToArabic[match[1]]; ok {
			number = num
		} else {
			return 0, fmt.Errorf("无法解析的数字: %s", match[1])
		}

		unit, unitOk := unitMap[match[2]]
		if !unitOk {
			return 0, fmt.Errorf("无法解析的单位: %s", match[2])
		}

		if unit < lastUnitValue {
			result += currentValue
			currentValue = 0
		}

		currentValue = number * unit
		lastUnitValue = unit
	}

	result += currentValue

	return result, nil
}

func main() {
	text := "openStack完成，加九百一十二分"
	number, err := convertChineseNumber(text)
	if err != nil {
		fmt.Println("错误:", err)
	} else {
		fmt.Printf("%s 转换为: %d\n", text, number)
	}
}
